package com.retry.task.admin.infrastructure.netty;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.retry.task.admin.biz.service.ServerExecutorBizService;
import com.retry.task.core.executor.ExectorAdapterImpl;
import com.retry.task.core.executor.IExectorAdapter;
import com.retry.task.core.server.RetryTaskServer;
import com.retry.task.core.utils.threadPool.RetryTaskThreadPoolExector;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/4/30  00:49
 * @Description TODO
 */
@Service
public class ServerNettyService implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerNettyService.class);
    @Autowired
    ServerExecutorBizService serverExecutor;

    private RetryTaskServer retryTaskServer;

    @Override
    public void afterPropertiesSet() throws Exception {
        RetryTaskThreadPoolExector taskThreadPoolExector = new RetryTaskThreadPoolExector(
            8,
            200,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(),
            new BasicThreadFactory.Builder().namingPattern("retry-task-server").build(),
            new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    throw new RuntimeException("RetryTaskServer bizThreadPool is EXHAUSTED!");
                }
            });
        IExectorAdapter iExectorAdapter = new ExectorAdapterImpl(serverExecutor);
        retryTaskServer = new RetryTaskServer(taskThreadPoolExector,iExectorAdapter,9999);
        retryTaskServer.start();
        LOGGER.info("------------------retry-task netty server start sucess---------------------");
    }
}
